package main.kotlin.network.server

import java.io.*
import java.net.ServerSocket
import java.net.Socket
import java.nio.charset.StandardCharsets
import java.util.concurrent.Executors

class ServerImpl() : Server() {

    var threadPool = Executors.newCachedThreadPool()
//    var threadPool1 = Executors.newScheduledThreadPool(4)

    override fun openServer(port: Int) {
        val serverSocket = if (port>0xFFFF || port<=1024) ServerSocket(defaultPort)  else ServerSocket(port)

        println("server is running...")
        while (true) {
            val sock = serverSocket.accept()
            println("connected from " + sock.remoteSocketAddress)
            threadPool.submit(Handler(sock))
        }
    }

    override fun closeServer(port: Int) {
        if (!threadPool.isShutdown){
            threadPool.shutdownNow()
        }
    }

    internal class Handler(var sock: Socket) : Runnable {
        override fun run() {
            try {
                sock.apply {
                    val input = getInputStream()
                    val output = getOutputStream()
                    handle(input,output)
                }
            } catch (e: Exception) {
                try {
                    sock.close()
                } catch (ioe: IOException) {
                }
                println("client disconnected.")
            }
        }

        @Throws(IOException::class)
        private fun handle(input: InputStream, output: OutputStream) {
            val writer = BufferedWriter(OutputStreamWriter(output, StandardCharsets.UTF_8))
            val reader = BufferedReader(InputStreamReader(input, StandardCharsets.UTF_8))
            writer.write("hello\n")
            writer.flush()
            while (true) {
                val s = reader.readLine()
                if (s == "bye") {
                    writer.write("bye\n")
                    writer.flush()
                    break
                }
                writer.write("ok: $s\n")
                writer.flush()
            }
        }
    }

}